<!--  -->
<template>
    <div class=''>
        <!-- 面包屑导航区，图标分隔符 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
            </el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <el-row>
                <el-col :span="20">
                    <el-button type="primary" @click="addRoleDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>

            <!-- 表格数据 -->
            <el-table :data="rolesList" border stripe>
                <!-- 展开列 -->
                <el-table-column label="具体权限" type="expand" width="80px">
                    <template slot-scope="scope">
                        <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
                            :class="['bdbottom',i1===0?'bdtop':'']" class="vcenter">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag type="primary" closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二、三级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环嵌套渲染二级权限 -->
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id"
                                    :class="[i2===0?'':'bdtop']" class="vcenter">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                                            {{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>{{scope.row}}</pre> -->

                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" icon="el-icon-edit" type="primary"
                            @click="showEditRoleDialog(scope.row.id)">编辑
                        </el-button>
                        <el-button size="mini" icon="el-icon-delete" type="danger"
                            @click="removeRoleById(scope.row.id)">删除</el-button>
                        <el-button size="mini" icon="el-icon-setting" type="warning" @click="showSetRightDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%">
            <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc" placeholder="角色描述"></el-input>
                </el-form-item>
            </el-form>
            <span class="btns">
                <el-button @click="addRoleDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="addRole">确定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="50%">
            <el-form :model="editRoleForm" :rules="addRoleFormRules" ref="editRoleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc" placeholder="角色描述"></el-input>
                </el-form-item>
            </el-form>
            <span class="btns">
                <el-button @click="editRoleDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="editRole">确定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%"
        @close="setRightDialogClosed">
            <!-- node-key  选中节点就是选中对应的id值 default-expand-all是否展开所有节点-->
            <el-tree :data="rightsList" :props="treePros" show-checkbox node-key="id"
             default-expand-all
             :default-checked-keys="defKeys"
             ref="treeRef"></el-tree>
            <span class="btns">
                <el-button @click="setRightDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="addRights">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
    //例如：import 《组件名称》 from '《组件路径》';

    export default {
        //import引入的组件需要注入到对象中才能使用
        name: 'Roles',
        components: {},
        props: {},
        data() {
            //这里存放数据
            return {
                rolesList: [],//所有角色列表信息
                addRoleDialogVisible: false,//添加角色对话框是否显示
                editRoleDialogVisible: false,//编辑角色对话框是否显示
                setRightDialogVisible: false,//是否显示分配权限对话框
                addRoleForm: {
                    roleName: '',//角色名称
                    roleDesc: '',//角色描述
                },//添加角色表单数据
                addRoleFormRules: {//添加表单数据的校验规则
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                },
                editRoleForm: {},//编辑用户表单
                rightsList: [],//所有权限的数据
                treePros: {
                    label: 'authName',
                    children: 'children',
                },//树形控件的属性绑定对象
                defKeys:[],//当前角色已有权限的id
                roleId:'',//当前即将分配权限的角色的id
            };
        },
        //监听属性 类似于data概念
        computed: {},
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            //获取所有角色列表信息
            async getRolesList() {
                const { data: res } = await this.$http.get('roles');
                // console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.rolesList = res.data;
            },

            //添加角色
            async addRole() {
                const { data: res } = await this.$http.post('roles', this.addRoleForm);
                // console.log(res);
                if (res.meta.status !== 201) {
                    return this.$message.error(res.meta.msg);
                }
                this.$message.success(res.meta.msg);
                this.addRoleDialogVisible = false;//关闭对话框
                this.getRolesList();//刷新页面数据
            },

            //显示编辑用户对话框 ,根据id查询角色信息
            async showEditRoleDialog(id) {
                //显示对话框
                this.editRoleDialogVisible = true;
                const { data: res } = await this.$http.get('roles/' + id);
                // console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.editRoleForm = res.data;
            },

            //编辑角色
            async editRole() {
                console.log(this.editRoleForm);
                const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
                this.editRoleDialogVisible = false;//关闭对话框
                this.getRolesList();//刷新数据
            },

            //删除角色
            async removeRoleById(id) {
                //删除之前弹框询问是否删除
                const confirmResult = await this.$confirm('此操作将永久删除该角色，是否继续？', '提示', {
                    confirmButtonTest: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).catch(error => error)

                //如果用户点了取消按钮返回的是字符串cancle
                //如果用户点击了确定按钮返回的是字符串confirm
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除');
                }

                const { data: res } = await this.$http.delete('roles/' + id);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
                this.getRolesList();//更新页面数据
            },

            //根据id删除对应的权限
            async removeRightById(role, id) {
                //弹框提示用户是否要删除
                //删除之前弹框询问是否删除
                const confirmResult = await this.$confirm('此操作将永久删除该权限，是否继续？', '提示', {
                    confirmButtonTest: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).catch(error => error)

                //如果用户点了取消按钮返回的是字符串cancle
                //如果用户点击了确定按钮返回的是字符串confirm
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除');
                }
                const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + id);
                // console.log(res);
                if (res.meta.status != 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);

                // this.getRolesList();
                role.children = res.data;

            },

            //展示分配权限的对话框
            async showSetRightDialog(role) {
                this.roleId=role.id;//将当前角色的id保存一下
                //获取所有权限的数据
                const { data: res } = await this.$http.get('rights/tree');
                if (res.meta.status != 200) return this.$message.error(res.meta.msg);
                // console.log(res);
                this.rightsList = res.data;

                this.setRightDialogVisible = true;

                //递归获取三级节点的id
                this.getLeafKeys(role,this.defKeys);

            },

            //通过递归的形式获取角色下所有三级权限的id
            getLeafKeys(node,arr){
                // 判断节点是否三级节点
                if(!node.children){
                    return arr.push(node.id);
                }
                node.children.forEach(item=>{
                    this.getLeafKeys(item,arr);
                })   
            },

            //关闭分配权限对话框时清空LearKeys
            setRightDialogClosed(){
                this.defKeys=[];
            },

            //点击为角色分配权限
            async addRights(){
                const keys=[
                    ...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()
                ];//获取所有选中和半选中权限的id
            
                const idStr=keys.join(',');//将keys拼接成,链接的额字符串
                const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr});
                if (res.meta.status != 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
                this.setRightDialogVisible=false;//关闭对话框
                this.getRolesList();//刷新数据
            },
        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {
            this.getRolesList();//获取所有角色列表信息
        },
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {

        },
        beforeCreate() { }, //生命周期 - 创建之前
        beforeMount() { }, //生命周期 - 挂载之前
        beforeUpdate() { }, //生命周期 - 更新之前
        updated() { }, //生命周期 - 更新之后
        beforeDestroy() { }, //生命周期 - 销毁之前
        destroyed() { }, //生命周期 - 销毁完成
        activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
    }
</script>
<style scoped lang='scss'>
    .btns {
        display: flex;
        justify-content: flex-end;
    }

    .el-tag {
        margin: 7px;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>